package mianshi.singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author: Tangxz
 * @email: 1171702529@qq.com
 * @cate: 2020/11/16 16:41
 */
//阻挡反射
public class LazyMan2 {

    private LazyMan2(){
        synchronized (LazyMan2.class){
            if (lazyMan2!=null){
                throw new RuntimeException("不要试图用反射破坏单例模式");
            }
        }
    }
    private volatile static LazyMan2 lazyMan2;

    public static LazyMan2 getInstance(){
        if (lazyMan2==null){
            synchronized (LazyMan.class){
                if (lazyMan2==null){
                    lazyMan2 = new LazyMan2();
                }
            }
        }
        return lazyMan2;
    }
}

class Demo02{
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        LazyMan2 instance = LazyMan2.getInstance();
        //反射
        Constructor<LazyMan2> declaredConstructor = LazyMan2.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);

        LazyMan2 instance2 = declaredConstructor.newInstance();


        System.out.println(instance==instance2);

    }
}